<template>
  <div class="p-3">
    <a-card style="height: 820px" :bordered="false">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="修改时间">
          <a-range-picker v-model:value="searchForm.time" />
        </a-form-item>
        <a-form-item label="所属项目">
          <a-tree-select
            v-model:value="searchForm.comId"
            tree-node-filter-prop="label"
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择所属项目"
          />
        </a-form-item>
        <a-form-item label="修改人">
          <a-tree-select
            v-model:value="searchForm.operator"
            tree-data-simple-mode
            allow-clear
            style="width: 150px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="selectList"
            placeholder="请选择操作人"
            :load-data="onLoadData"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onSearch">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="showSmsModal">新增消息模版</a-button>
        </a-form-item>
      </a-form>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        class="mt-3"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'action'">
            <a-button type="link" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm
              placement="bottom"
              ok-text="是"
              cancel-text="否"
              title="确认删除吗？"
              @confirm="handleDelete(record)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑短信模版弹窗 -->
    <a-modal
      :visible="smsModalVisible"
      :title="isEdit ? '新增模版' : '编辑模版'"
      width="400px"
      @ok="handleSmsOk"
      @cancel="handleSmsCancel"
    >
      <a-form :model="smsFormData" layout="vertical">
        <a-form-item label="所属项目">
          <a-tree-select
            v-model:value="smsFormData.comId"
            tree-node-filter-prop="label"
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择所属项目"
          />
        </a-form-item>
        <a-form-item label="模版名称">
          <a-input
            v-model:value="smsFormData.templateName"
            placeholder="请输入模版名称"
          />
        </a-form-item>
        <a-form-item label="模版类型">
          <a-select v-model:value="smsFormData.templateType">
            <a-select-option value="普通短信">普通短信</a-select-option>
            <a-select-option value="催费短信">催费短信</a-select-option>
            <a-select-option value="公众号">公众号</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="模版内容">
          <a-textarea
            v-model:value="smsFormData.templateContent"
            placeholder="请输入模版内容"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import { message } from 'ant-design-vue';
import {
  getSmsTemplateInfo,
  addSmsTemplateInfo,
  editSmsTemplateInfo,
  delSmsTemplateInfo,
} from '#/api/core/setting';
import { getOperatorApi } from '#/api/core/statistical';
import { getCompanyTree } from '#/api/core/develop';
import dayjs from 'dayjs';

// 弹窗状态
const smsModalVisible = ref(false);
// 编辑状态标志
const isEdit = ref(false);
// 当前编辑的记录ID
const currentEditId = ref('');

const comanyList = ref<[]>([]);
const selectList = ref<[]>([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      // console.log(tree)
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData || [];
    // console.log(comanyList.value);
  });
};
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      // console.log(res);
      selectList.value = (res || []).map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    // console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          // console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        // console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
getTableData();
getList();
// 表单数据
const searchForm = reactive({
  comId: undefined,
  time: '',
  operator: undefined,
});
const smsFormData = reactive({
  comId: '',
  templateName: '',
  templateType: undefined,
  templateContent: '',
});

// 表格数据
const dataSource = ref([]);

// 分页配置
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const onSearch = () => {
  const query = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    comId: searchForm.comId,
    time: searchForm.time
      ? dayjs(searchForm.time[0]).format('YYYY-MM-DD') +
        ',' +
        dayjs(searchForm.time[1]).format('YYYY-MM-DD')
      : '',
    nickName: searchForm.operator ?? '',
  };
  getSmsTemplateInfo(query).then((res: any) => {
    // console.log(res);
    dataSource.value = res.data.data;
    pagination.total = res.data.total;
  });
};
// 显示弹窗方法
const showSmsModal = (edit = true, record = null) => {
  isEdit.value = edit;
  if (!edit && record) {
    // 编辑模式，填充表单数据
    currentEditId.value = record.id;
    smsFormData.comId = record.comId;
    smsFormData.templateName = record.templateName;
    smsFormData.templateType = record.templateType;
    smsFormData.templateContent = record.templateContent;
  } else {
    // 新增模式，重置表单数据
    currentEditId.value = '';
    smsFormData.comId = '';
    smsFormData.templateName = '';
    smsFormData.templateType = undefined;
    smsFormData.templateContent = '';
  }
  smsModalVisible.value = true;
};

// 处理编辑按钮点击
const handleEdit = (record) => {
  showSmsModal(false, record);
};

// 处理确认操作
const handleSmsOk = () => {
  // 表单验证
  if (!smsFormData.comId) {
    message.error('请选择所属项目');
    return;
  }
  if (!smsFormData.templateName) {
    message.error('请输入模版名称');
    return;
  }
  if (!smsFormData.templateType) {
    message.error('请选择模版类型');
    return;
  }
  if (!smsFormData.templateContent) {
    message.error('请输入模版内容');
    return;
  }
  console.log(isEdit.value);
  // 根据编辑状态调用不同的API
  if (!isEdit.value) {
    // 编辑模式
    const params = {
      id: currentEditId.value,
      ...smsFormData,
    };
    editSmsTemplateInfo(params)
      .then((res: any) => {
        if (res.data.code === 200) {
          message.success('编辑成功');
          smsModalVisible.value = false;
          onSearch(); // 刷新表格数据
        } else {
          message.error(res.msg || '编辑失败');
        }
      })
      .catch((error) => {
        console.error('编辑失败:', error);
        message.error('编辑失败');
      });
  } else {
    // 新增模式
    addSmsTemplateInfo(smsFormData)
      .then((res: any) => {
        if (res.data.code === 200) {
          message.success('新增成功');
          smsModalVisible.value = false;
          onSearch(); // 刷新表格数据
        } else {
          message.error(res.msg || '新增失败');
        }
      })
      .catch((error) => {
        console.error('新增失败:', error);
        message.error('新增失败');
      });
  }
};

// 处理取消操作
const handleSmsCancel = () => {
  smsModalVisible.value = false;
  // 重置编辑状态和表单数据
  isEdit.value = false;
  currentEditId.value = '';
  smsFormData.comId = '';
  smsFormData.templateName = '';
  smsFormData.templateType = undefined;
  smsFormData.templateContent = '';
};

const columns = [
  {
    title: '项目',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '模版名称',
    dataIndex: 'templateName',
    key: 'templateName',
    align: 'center',
  },
  {
    title: '模版内容',
    dataIndex: 'templateContent',
    key: 'templateContent',
    align: 'center',
  },
  {
    title: '模版类型',
    dataIndex: 'templateType',
    key: 'templateType',
    align: 'center',
  },
  {
    title: '修改人',
    dataIndex: 'updatePer',
    key: 'updatePer',
    align: 'center',
  },
  {
    title: '修改时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
  },
];
const handleDelete = (e: any) => {
  delSmsTemplateInfo(e.id).then((res: any) => {
    console.log(res);
    if (res.data.code == 200) {
      message.success('删除成功');
      onSearch();
    } else {
      message.error('删除失败');
    }
  });
};
</script>
<style scoped></style>
